'use strict';

const RouterService = require('../base');

class SupplierQuoteService extends RouterService {
  static get modelName() {
    return 'Business.SupplierQuote';
  }

  getListInclude() {
    return [
      {
        model: this.ctx.model.Business.Supplier,
        as: 'supplier'
      },
      {
        model: this.ctx.model.Business.Dish,
        as: 'dish'
      }
    ]
  }


  // 批量创建供应商报价
  async batchCreate(payload) {
    const { monthly_bidding_supplier_id, monthly_bidding_id, supplier_id, quotes } = payload;
    // 创建事务
    const transaction = await this.ctx.model.transaction();
    try {
      // 更新月度报价关联供应商表的状态
        await this.ctx.model.Business.BiddingSupplier.update({
          status: 2
        }, {
          where: {
            id: monthly_bidding_supplier_id
          },
        });
        // 先删除该供应商的现有报价
        await this.model.destroy({
          where: {
            monthly_bidding_supplier_id,
            monthly_bidding_id,
            supplier_id
          },
          transaction
        });
        // 准备批量插入的数据
        const quoteData = quotes.map(quote => ({
          monthly_bidding_supplier_id,
          monthly_bidding_id,
          supplier_id,
          dish_id: quote.dish_id,
          quoted_price: quote.quoted_price,
          status: 1
        }));

        // 批量创建报价记录
        const result = await this.model.bulkCreate(quoteData, { transaction });
        transaction.commit()
        return result;
    } catch (error) {
      await transaction.rollback();
      throw error;
    }
  }
}

module.exports = SupplierQuoteService;
